package com.mming.sso.controller;

import com.mming.sso.bean.ResponseWrapper;
import com.mming.sso.bean.UserInfo;
import com.mming.sso.entity.User;
import com.mming.sso.service.UserService;
import com.mming.sso.util.RequestUtil;
import com.mming.sso.util.ResponseUtil;
import com.mming.sso.util.TimeUtil;
import com.mming.sso.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@EnableAutoConfiguration
public class UserController {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    HttpServletRequest request;

    @Resource
    HttpServletResponse response;

    @Autowired
    private UserService userService;

    @PostMapping(value = "/user/info/")
    public ResponseWrapper userInfo(@RequestParam("username") String username) {
        UserInfo userInfo = userService.getUserInfoByUsername(username);
        if (userInfo == null)
            return ResponseUtil.response(801);
        else {
            return ResponseUtil.responseWithData(200, userInfo);
        }
    }

    @PostMapping(value = "/login")
    public ResponseWrapper login(@RequestParam(value = "username") String username,
                                 @RequestParam(value = "password") String password) {
        String ip = RequestUtil.getIP(request);
        if (userService.login(username, password, ip)) {
            //签发token
            String token = TokenUtil.sign(username, TokenUtil.SECRET);
            //new Cookie对象，并设置cookie
            Cookie cookie = new Cookie("_tk", token);
            cookie.setMaxAge(TokenUtil.EXPIRE_TIME);
            response.addCookie(cookie);
            //将token添加到redis
            String key = TokenUtil.generateLoginKey(username);
            redisTemplate.opsForValue().set(key, token, TokenUtil.EXPIRE_TIME, TimeUnit.MILLISECONDS);

            return ResponseUtil.responseWithData(200, token);
        } else
            return ResponseUtil.response(801);
    }

    @PostMapping(value = "/register")
    public ResponseWrapper register(@Valid User user) {
        int registerResult = userService.register(user);
        switch (registerResult) {
            case -1:
                return ResponseUtil.response(800);
            case 0:
                log.error(user.getUsername() + " register fail in " + TimeUtil.getDatetime());
                return ResponseUtil.response(500);
            default:
                return ResponseUtil.responseWithData(200, registerResult);
        }
    }

    @DeleteMapping(value = "/user/delete/")
    public ResponseWrapper ban(@RequestParam(value = "username") String username) {
        if (userService.banUser(username) != -1) {
            try {
                boolean deleteRes = redisTemplate.delete(TokenUtil.generateLoginKey(username));
                log.info(username + "'s token is deleted success");
                return ResponseUtil.response(200);
            } catch (NullPointerException e) {
                log.info(username + " is not a alive user in system");
                log.warn(e.getMessage());
                return ResponseUtil.response(500);
            }
        } else
            return ResponseUtil.response(801);
    }
}
